import { DD_SYSTEM } from '@/constants/api-pre';
import { request } from '@/service/request';

/**
 * menu type
 *
 * - "1": directory
 * - "2": menu
 * - "3": button"
 * - "4": extlink
 */
export type MenuType = '1' | '2' | '3' | '4';

/**
 * icon type
 *
 * - "1": iconify icon
 * - "2": local icon
 */
export type IconType = '1' | '2';

export type MenuPropsOfRoute = Pick<
  import('vue-router').RouteMeta,
  'i18nKey' | 'keepAlive' | 'constant' | 'sort' | 'href' | 'hideInMenu' | 'activeMenu' | 'multiTab' | 'fixedIndexInTab'
>;

export type Menu = Api.Common.CommonRecord<{
  /** parent menu id */
  parentId: number;
  /** menu type */
  menuType: MenuType;
  /** menu name */
  menuName: string;
  /** route name */
  routeName: string;
  /** route path */
  routePath: string;
  /** component */
  component?: string;
  /** iconify icon name or local icon name */
  icon: string;
  /** icon type */
  iconType: IconType;
  /** children menu */
  children?: Menu[] | null;
  /** permission */
  permission?: string;
  /** href open type */
  hrefOpenType?: number | null;
}> &
  MenuPropsOfRoute;

/** menu list */
export type MenuList = Api.Common.PaginatingQueryRecord<Menu>;

export type MenuTree = {
  id: number;
  label: string;
  pId: number;
  children?: MenuTree[];
};

/** menu search params */
export type MenuSearchParams = CommonType.RecordNullable<
  Pick<Menu, 'menuName' | 'status'> & Api.Common.CommonSearchParams
>;

/** get menu list */
export function fetchGetMenuList(params?: MenuSearchParams) {
  return request<MenuList>({
    url: `${DD_SYSTEM}/menus/tree`,
    method: 'get',
    params
  });
}

/** get all pages */
export function fetchGetAllPages() {
  return request<string[]>({
    url: `${DD_SYSTEM}/menus/pages/all`,
    method: 'get'
  });
}

/** 获取简易菜单树供授权使用 */
export function fetchGetSimpleMenuTree() {
  return request<MenuTree[]>({
    url: `${DD_SYSTEM}/menus/simple/tree`,
    method: 'get'
  });
}

/**
 * 新增菜单
 *
 * @param data
 */
export function createMenu(data: Menu) {
  return request<boolean>({
    url: `${DD_SYSTEM}/menus`,
    method: 'post',
    data
  });
}

/**
 * 编辑菜单
 *
 * @param id
 * @param data
 */
export function updateMenu(id: number, data?: Menu) {
  return request<boolean>({
    url: `${DD_SYSTEM}/menus/${id}`,
    method: 'put',
    data
  });
}

/**
 * 删除菜单
 *
 * @param ids
 */
export function deleteMenus(ids: string) {
  return request<boolean>({
    url: `${DD_SYSTEM}/menus/${ids}`,
    method: 'delete'
  });
}

/**
 * 获取角色菜单id列表
 *
 * @param roleId
 */
export function fetchMenuIdListByRoleId(roleId: number) {
  return request<number[]>({
    url: `${DD_SYSTEM}/permission/role/${roleId}/menus`,
    method: 'get'
  });
}
